package com.lxxie.com.lxxie.service.impl;

import com.lxxie.com.lxxie.service.SqlHistoryService;
import com.lxxie.common.util.MD5Util;
import com.lxxie.dao.SqlHistoryRepository;
import com.lxxie.entity.SqlHistory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * Created by xielx on 21/1/22 14:37
 */
@Service
public class SqlHistoryServiceImpl implements SqlHistoryService {
        @Autowired
        private SqlHistoryRepository repository;

        @Transactional
        @Override
        public void save(String sql) {
                String id = createId(sql);
                Optional<SqlHistory> entity = repository.findById(id);
                if (entity.isPresent()) {
                        SqlHistory bean = entity.get();
                        bean.setGxsj(new Date());
                        repository.saveAndFlush(bean);
                }else{
                        SqlHistory bean = new SqlHistory();
                        bean.setXh(id);
                        bean.setSql(sql);
                        repository.saveAndFlush(bean);
                }
        }

        @Override
        public List<SqlHistory> querySqlHis() {
                return repository.findTop100His();
        }

        @Transactional
        @Override
        public void delHis(String xh) {
                repository.deleteById(xh);
        }

        private String createId(String input) {
                return MD5Util.MD5(input);
        }
}
